package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dto.request.loan.PushProjectRequestDTO;
import com.niiwoo.civet.trade.service.local.common.ProjectCommonService;
import com.niiwoo.civet.trade.service.local.loan.SpeedLoanDispenseChannelService;
import com.niiwoo.civet.trade.service.local.project.ProjectLocalService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * 标的分端监听器
 * @author TomXue
 * @since 2018-09-13
 */
@Component
@Slf4j
public class AllotChannelListener {
    @Autowired
    SpeedLoanDispenseChannelService speedLoanDispenseChannelService;
    @Autowired
    ProjectLocalService projectLocalService;

    @RabbitListener(queues = {MqConstant.ALLOT_CHANNEL_QUEUE})
    public void allotChannelHandler(PushProjectRequestDTO pushProjectRequestDTO, Message message, Channel channel) throws IOException {
        try {
            log.info("标的分端通知,标的ID={},请求参数={}", pushProjectRequestDTO == null ? null : pushProjectRequestDTO.getProjectId(), JSON.toJSONString(pushProjectRequestDTO));
            projectLocalService.allotChannel(pushProjectRequestDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (BizException bizE){
            log.error("标的分端通知,标的ID={},发生业务异常,原因={}", pushProjectRequestDTO == null ? null : pushProjectRequestDTO.getProjectId(), bizE);
            if(bizE.getErrorCode().equals("TRD10027")){
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                return;
            }
        } catch(Exception e){
            log.error("标的分端通知,标的ID={},发生系统异常,原因={}", pushProjectRequestDTO == null ? null : pushProjectRequestDTO.getProjectId(), e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
    }
}
